package com.tgd.RingtoneContactManager;

import android.app.Activity;
import android.app.ListFragment;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class ContactFragment extends ListFragment {

    private SimpleActivity _activity;
    private DAO _dao;
    private Contact _selectedContact;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        _activity = (SimpleActivity) getActivity();

        _dao = DAO.getInstance(_activity);

        setHasOptionsMenu(true);

        ContactAdapter ea = new ContactAdapter(_activity, _dao.getContacts(Contact.Filter.ALL,
                Contact.Sort.NAME));
        setListAdapter(ea);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Activity.RESULT_OK == resultCode) {
            Uri pickedItem = (Uri) data.getExtras().get(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

            // if silent is picked, then pickedItem is null
            // if default is picked, then pickedItem.toString ==
            // "content://settings/system/ringtone"

            if (android.provider.Settings.System.DEFAULT_RINGTONE_URI.compareTo(pickedItem) == 0) {
                _dao.setDefault(_selectedContact);
            } else {
                _dao.set(pickedItem, _selectedContact);
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.contact_actions, menu);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        _selectedContact = ((ContactAdapter.ViewHolder) v.getTag()).contact;
        if (_actionMode == null) {
            _actionMode = _activity.startActionMode(mActionModeCallback);
        }
        _actionMode.setTitle(_selectedContact.getName());

        _actionMode.getMenu().findItem(R.id.contactSetAsDefault)
                .setVisible(!(_selectedContact.getRingtoneId().compareTo("") == 0));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        ContactAdapter ea;

        switch (item.getItemId()) {
        case R.id.contactFilterAll:
            ea = new ContactAdapter(_activity, _dao.getContacts(Contact.Filter.ALL));
            setListAdapter(ea);
            break;
        case R.id.contactFilterCustom:
            ea = new ContactAdapter(_activity, _dao.getContacts(Contact.Filter.CUSTOM));
            setListAdapter(ea);
            break;
        case R.id.contactFilterDefault:
            ea = new ContactAdapter(_activity, _dao.getContacts(Contact.Filter.DEFAULT));
            setListAdapter(ea);
            break;
        case R.id.contactFilterDirty:
            ea = new ContactAdapter(_activity, _dao.getContacts(Contact.Filter.DIRTY));
            setListAdapter(ea);
            break;
        case R.id.contactSortContactName:
            ea = new ContactAdapter(_activity, _dao.getContacts(Contact.Sort.NAME));
            setListAdapter(ea);
            break;
        case R.id.contactSortRingtoneName:
            ea = new ContactAdapter(_activity, _dao.getContacts(Contact.Sort.RINGTONE));
            setListAdapter(ea);
            break;
        default:
            break;
        }

        getListView().invalidateViews();
        item.setChecked(true);
        return true;
    }

    private ActionMode _actionMode;
    private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

        // Called when the action mode is created; startActionMode() was called
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.contact_context, menu);

            return true;
        }

        // Called each time the action mode is shown. Always called after
        // onCreateActionMode, but
        // may be called multiple times if the mode is invalidated.
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false; // Return false if nothing is done
        }

        // Called when the user selects a contextual menu item
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.contactPlay:
                _dao.play(_selectedContact);
                break;
            case R.id.contactStop:
                _dao.stop();
                break;
            case R.id.contactSetRingtone:
                // TODO: I need to handle for Silent, so far I haven't even
                // thought about it.
                Intent i = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);

                // TODO handle for default, and dirty, and silent, and DRM
                i.putExtra(
                        RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
                        _selectedContact.isSetToDefault() ? android.provider.Settings.System.DEFAULT_RINGTONE_URI
                                : Uri.parse(_selectedContact.getRingtoneId())).putExtra(
                        RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);

                startActivityForResult(i, 25);

                break;
            case R.id.contactSetAsDefault:
                _dao.setDefault(_selectedContact);
                break;
            default:
                return false;
            }
            return true;
        }

        // Called when the user exits the action mode
        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // TODO the DAO should be able to tell me if a change was made, if
            // not then don't reload the adapter.
            ContactAdapter ea = new ContactAdapter(_activity, _dao.getContacts());
            setListAdapter(ea);
            getListView().clearChoices();
            getListView().invalidateViews();
            _actionMode = null;
        }
    };
}
